package com.rongshu.view.userInfo.activity;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.rongshu.R;
import com.rongshu.utils.Common;
import com.rongshu.utils.Constant;
import com.rongshu.utils.LoginUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.userInfo.adapter.SystemsAdapter;
import com.rongshu.view.userInfo.entity.MessageInfo;
import com.rongshu.view.userInfo.entity.SystemMessage;
import com.rongshu.view.userInfo.iview.MessageClassifyView;
import com.rongshu.view.userInfo.listener.OnMsgFunctionClickListener;
import com.rongshu.view.userInfo.presenter.MessageClassifyPresenter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.rongshu.utils.UserInfoUtils.getUserId;

public class MessageClassifyActivity extends BaseActivity<MessageClassifyPresenter> implements MessageClassifyView, OnMsgFunctionClickListener {
    @BindView(R.id.txt_top_title)
    TextView txt_top_title;
    @BindView(R.id.txt_direct_count)
    TextView txt_direct_count;
    @BindView(R.id.txt_praise_count)
    TextView txt_praise_count;
    @BindView(R.id.txt_comment_count)
    TextView txt_comment_count;
    @BindView(R.id.txt_at_count)
    TextView txt_at_count;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.view_stub_empty)
    ViewStub viewStub;
    private View inflate;
    private RelativeLayout layoutEmpty;
    //manager
    private RecyclerView.LayoutManager manager = null;
    //adapter
    private SystemsAdapter adapter;
    //map
    private Map<String, Object> map = null;
    private int pageIndex = 1;
    private int pageSize = 10;
    //系统消息列表
    private List<SystemMessage.ResponseBean> systemMsgList;
    private MessageInfo.ResponseBean bean;

    @Override
    protected int initLayout() {
        return R.layout.activity_message_classify_view;
    }

    @Override
    protected void initView() {
        //set presenter
        setPresenter(new MessageClassifyPresenter(this), this);
        //设置title
        txt_top_title.setText("消息中心");
        //manager
        manager = new LinearLayoutManager(this);
        //adapter
        systemMsgList = new ArrayList<>();
        adapter = new SystemsAdapter(this, systemMsgList);
        adapter.setOnMsgFunctionListener(this);
        //添加自定义分割线
        DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(this, R.drawable.msg_center_divider));
        recyclerview.addItemDecoration(divider);
        //动画
        DefaultItemAnimator defaultItemAnimator = new DefaultItemAnimator();
        defaultItemAnimator.setRemoveDuration(100);
        recyclerview.setItemAnimator(defaultItemAnimator);
        //recyclerview
        recyclerview.setLayoutManager(manager);
        recyclerview.setAdapter(adapter);
        //触发自动刷新
        refreshLayout.autoRefresh();
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshlayout) {
                pageIndex = 1;
                refreshLayout.resetNoMoreData();
                getSystemMessage();
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                pageIndex++;
                getSystemMessage();
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }

    @Override
    protected void onResume() {
        super.onResume();
        getMsgCount();
    }

    /**
     * 请求系统消息
     */
    private void getSystemMessage() {
        //user_id
        int user_id = getUserId();
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("page", pageIndex);
        map.put("pagesize", pageSize);
        presenter.getSystemMessage(user_id,
                pageIndex, pageSize, Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 删除系统消息
     */
    private void getDeleteMsg(int obj_id) {
        map = new HashMap<>();
        map.put("obj_id", obj_id);
        map.put("type", Constant.DELETE_SYSTEM);
        presenter.getDeleteMsg(
                (int) map.get("obj_id"),
                (int) map.get("type"),
                Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 获取我的消息页面的未读信息数
     */
    public void getMsgCount() {
        //user_id
        int user_id = getUserId();
        if (user_id == 0) {
            LoginUtils.toLogin(this);
            return;
        }
        map = new HashMap<>();
        map.put("user_id", user_id);
        presenter.getMsgCount(user_id, Common.encryptionSign(map));
        map.clear();
    }

    @OnClick({R.id.layout_back, R.id.private_letter, R.id.praise_layout, R.id.comment_layout, R.id.at_layout})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_back:
                finish();
                break;
            case R.id.private_letter:
                Intent intent1 = new Intent(this, DirectMessageListActivity.class);
                if (bean != null) {
                    intent1.putExtra(Constant.INTENT_DATA, bean.getPrivatechatCount());
                }
                startActivity(intent1);
                break;
            case R.id.praise_layout:
                startActivity(new Intent(this, PraiseMeListActivity.class));
                break;
            case R.id.comment_layout:
                Intent intent2 = new Intent(this, CommentMeListActivity.class);
                if (bean != null) {
                    intent2.putExtra(Constant.INTENT_DATA, bean.getCommentCount());
                }
                startActivity(intent2);
                break;
            case R.id.at_layout:
                Intent intent3 = new Intent(this, AtMeListActivity.class);
                if (bean != null) {
                    intent3.putExtra(Constant.INTENT_DATA, bean.getAtMyMsgCount());
                }
                startActivity(intent3);
                break;
        }
    }

    /**
     * 系统消息回调
     */
    @Override
    public void onSystemMessage(SystemMessage systemMessage) {
        if (systemMessage != null) {
            List<SystemMessage.ResponseBean> authorDetailBeans = systemMessage.getResponse();
            if (refreshLayout.isRefreshing()) {//结束刷新
                refreshLayout.finishRefresh();
            }
            if (refreshLayout.isLoading()) {//结束加载
                refreshLayout.finishLoadmore();
            }
            if (pageIndex == 1) {
                systemMsgList.clear();
            }
            systemMsgList.addAll(authorDetailBeans);
            adapter.notifyDataSetChanged();
            if (authorDetailBeans.size() == 0) {//请求不到数据，证明没有更多了
                refreshLayout.finishLoadmoreWithNoMoreData();
            }
            if (systemMsgList.size() == 0) {//判断显示缺省页面
                showEmptyLayout();
            } else {
                hideEmptyLayout();
            }
        }
    }

    /**
     * 获取我的消息页面的未读信息数
     */
    @Override
    public void onMsgCount(MessageInfo info) {
        if (info.getErrCode() == 0) {
            bean = info.getResponse();
            if (bean == null) {
                return;
            }
            int directMsgCount = bean.getPrivatechatCount();
            int atMyMsgCount = bean.getAtMyMsgCount();
            int commentCount = bean.getCommentCount();
            int likeCount = bean.getLikeCount();
            //私信
            txt_direct_count.setText(String.valueOf(directMsgCount));
            txt_direct_count.setVisibility(directMsgCount == 0 ? View.GONE : View.VISIBLE);
            //赞
            txt_praise_count.setText(String.valueOf(likeCount));
            txt_praise_count.setVisibility(likeCount == 0 ? View.GONE : View.VISIBLE);
            //评论
            txt_comment_count.setText(String.valueOf(commentCount));
            txt_comment_count.setVisibility(commentCount == 0 ? View.GONE : View.VISIBLE);
            //@我
            txt_at_count.setText(String.valueOf(atMyMsgCount));
            txt_at_count.setVisibility(atMyMsgCount == 0 ? View.GONE : View.VISIBLE);
        } else {
            toast(info.getErrMsg());
        }
    }

    @Override
    public void onItemClick(int position) {
    }

    @Override
    public void onItemDeleteClick(final int position) {
        SystemMessage.ResponseBean bean = systemMsgList.get(position);
        getDeleteMsg(bean.getMessage_id());
        systemMsgList.remove(position);
        adapter.notifyItemRemoved(position);//注意这里
        adapter.notifyItemRangeChanged(position, systemMsgList.size() - position);//通知数据与界面重新绑定
    }


    @Override
    public void onUserHeaderClick(int userIdTo) {

    }

    /**
     * 显示缺省页面
     */
    private void showEmptyLayout() {
        if (inflate == null) {
            inflate = viewStub.inflate();
            layoutEmpty = inflate.findViewById(R.id.layout_empty);
            ImageView noDataImg = inflate.findViewById(R.id.no_data_img);
            TextView noDataHint = inflate.findViewById(R.id.no_data_hint);
            noDataImg.setImageResource(R.drawable.empty_message_bg);
            noDataHint.setText("信箱空空如也~");
        }
        layoutEmpty.setVisibility(View.VISIBLE);
    }

    /**
     * 隐藏缺省页面
     */
    private void hideEmptyLayout() {
        if (layoutEmpty != null) {
            layoutEmpty.setVisibility(View.GONE);
        }
    }
}
